package DBLayer;
import ModelLayer.*;
import java.sql.*;


public class DBKunde implements IFDBKunde {
	private Connection con;
	
	public DBKunde() {
		con = DBConnection.getInstance().getDBcon();
	}
	
	public Kunde findKunde(int kundeID, boolean retriveAssociation)
    {   String wClause = "  kundeid = '" + kundeID + "'";
        return singleWhere(wClause, retriveAssociation);
    }
	
	private Kunde singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		Kunde kObj = new Kunde();
                
	        String query =  buildQuery(wClause);
                System.out.println(query);
		try{ // read the employee from the database
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
                            kObj = buildKunde(results);
                            //assocaition is to be build
                            stmt.close();
                            
			}
                        else{ //no employee was found
                            kObj = null;
                        }
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return kObj;
	}
	
	private String buildQuery(String wClause)
	{
	    String query="SELECT kundeid, navn, adresse, bynavn, postnr, telefonnr, email  FROM kunde";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	
	private Kunde buildKunde(ResultSet results)
    {   Kunde kObj = new Kunde();
        try{ // the columns from the table emplayee  are used
              kObj.setKundeID(results.getInt("kundeid"));
              kObj.setNavn(results.getString("navn"));
              kObj.setAdresse(results.getString("adresse"));
              kObj.setByNavn(results.getString("bynavn"));
              kObj.setPostNr(results.getInt("postnr"));
              kObj.setTelefonNr(results.getInt("telefonnr"));
              kObj.seteMail(results.getString("email"));
              }
       catch(Exception e)
       {
           System.out.println("error in building the employee object");
       }
       return kObj;
    }
	
}
